package com.study.mongodb.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

public class SimpleMongoDaoImpl<T, PK extends Serializable> implements SimpleMongoDao<T, PK> {

    @Autowired
    private MongoOperations mongoOper;

    protected Class<T> entityClazz;
    /**
     * 字符串分隔的标志符号，现在用:表示，在关联查询的时候用。
     ***/
    private final String      splitMarker = "::";



    public SimpleMongoDaoImpl(MongoOperations mongoOper) {
        this.mongoOper = mongoOper;
        this.entityClazz = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public void save(T entity) {
        mongoOper.save(entity);
    }

    @Override
    public void update(T entity) {
        mongoOper.save(entity);
    }

    @Override
    public void saveOrUpdate(T entity) {
        mongoOper.save(entity);
    }

    @Override
    public void saveOrUpdate(Collection<T> entities) {
        for (T entity : entities) {
            mongoOper.save(entity);
        }
    }

    @Override
    public void delete(T entity) {
        mongoOper.remove(entity);
    }

    @Override
    public void deleteAll(Collection<T> entities) {
        for (T entity : entities) {
            mongoOper.remove(entity);
        }
    }

    @Override
    public void deleteById(PK id) {
        mongoOper.remove(new Query(Criteria.where("_id").is(id)), entityClazz);
    }

    @Override
    public T get(PK id) {
        return mongoOper.findById(id, entityClazz);
    }

    @Override
    public List<T> getAll() {
        return this.mongoOper.findAll(entityClazz);
    }
}
